package com.example.flashApp.usage

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import java.util.Date

class UsageViewModel(application: Application) : AndroidViewModel(application) {

    private val repository = UsageRepository(application)
    private val _usageStats = MutableLiveData<List<UsageStat>>()
    val usageStats: LiveData<List<UsageStat>> get() = _usageStats

    private val _loading = MutableLiveData<Boolean>()
    val loading: LiveData<Boolean> get() = _loading

    private val _error = MutableLiveData<String?>()
    val error: LiveData<String?> get() = _error

    fun loadUsageStats(startDate: Date, endDate: Date) {
        viewModelScope.launch {
            _loading.value = true
            try {
                val usageEntities = repository.getUsageBetweenDates(startDate, endDate)
                _usageStats.value = usageEntities.map { entity ->
                    UsageStat(
                        packageName = entity.packageName,
                        duration = entity.duration,
                        lastUsed = entity.lastUsed
                    )
                }
                _error.value = null
            } catch (e: Exception) {
                _error.value = e.message
            } finally {
                _loading.value = false
            }
        }
    }

    fun deleteOldData(olderThan: Date) {
        viewModelScope.launch {
            repository.deleteOldData(olderThan)
        }
    }
}
